<?php
namespace app\admin\controller;
use think\Request;
use \think\Db;
use app\common\model\Dog as DogModel;
use app\common\model\Area as AreaModel;

class Stray extends \app\admin\controller\Base
{
    protected $res = array(
        'index'   => array('css' => '2,3,4', 'js' => 'list,My97DatePicker'),
        'statistics'   => array('css' => '2,3,4', 'js' => 'echart,My97DatePicker'),
        'column'   => array('css' => '2,3,4', 'js' => 'echart,My97DatePicker'),
        'details'   => array('css' => '2,3,4', 'js' => 'echart,My97DatePicker'),
    );
    public function index(){

        $DogModel = new DogModel();
        $AreaModel = new AreaModel();
        $search = input('get.search/a');
        $page = input('get.page');
        $search = $this->search($search, $page);
        $list = $DogModel->strayDogInfo(15,$search);
        //主人年龄
        foreach($list as $key => &$vo){
            if($vo['user_card'] != ''){
                $vo['user_card'] = $this->getAgeByID($vo['user_card']);
            }else{
                $vo['user_card'] = '';
            }
        }
        $action = '/' . Request::instance()->controller() . '/' . Request::instance()->action();
        $wherePro['level'] = 1;
        if($search[1]!=''){
            $whereCity['pid'] = $search[1];
        }else{
            $whereCity['pid'] = 2;
        }
        if($search[2]!=''){
            $whereDistrict['pid'] = $search[2];
        }else{
            $whereDistrict['pid'] = 52;

        }
        $province =$AreaModel->selectArea($wherePro);
        $city =$AreaModel->selectArea($whereCity);
        $district =$AreaModel->selectArea($whereDistrict);
        $this->assign(
            array(
                'action'=>$action,
                'list'=>$list,
                'page'=>$page,
                'search' => $search,
                'province' => $province,
                'city' => $city,
                'district' => $district,
                'dog_status'=>$DogModel::$dog_status,
                'user_attestation'=>$DogModel::$user_attestation,
                'user_gender'=>$DogModel::$user_gender
            )
        );
        return $this->fetch();
    }
    /**
     * 查询市
     */
    public function city($city){
//        $city = $_POST['city'];
        $cityArray = Db::table('up_area')->where('pid',$city)->select();
        $data['cityArray'] = $cityArray;
        return json($data);
    }
    /**
     * 查询区
     */
    public function area($area){
//        $area = $_POST['area'];
        $cityArray = Db::table('up_area')->where('pid',$area)->select();
        $data['cityArray'] = $cityArray;
        return json($data);
    }
    /**
     * 导出excel
     * @return $data  需要导出的数据
     */
    public function excelDownload(){
        $DogModel = new DogModel();
        $search = input('post.search/a');
        $res = $DogModel->excelData($search, 1, 'dog_status');
        $result = array();
        foreach ($res as $key=>$vo){
            $result[$key]['dog_id'] = $vo['dog_id'];//流浪狗ID
//            $result[$key]['udf_name'] = $vo['udf_name'];
            //流浪狗状态

            if($vo['dog_status']==1){
                $result[$key]['dog_status'] = '待救助';
            }elseif ($vo['dog_status']==2){
                $result[$key]['dog_status'] = '已救助';
            }elseif ($vo['dog_status']==3){
                $result[$key]['dog_status'] = '失踪';
            }else{
                $result[$key]['dog_status'] = '';
            }
            //发布时间
            $dog_time = strtotime($vo['dog_release_time']);
            $result[$key]['dog_time'] = date('Y', $dog_time).'/'.date('m', $dog_time).'/'.date('d', $dog_time).' '.date('H', $dog_time).':'.date('i', $dog_time);


            $result[$key]['province'] = $vo['province'];//发现地点--省
            $result[$key]['city'] = $vo['city'];//发现地点--市
            $result[$key]['area'] = $vo['district'];//发现地点--区
            $result[$key]['dog_add'] = $vo['dog_add'];//发现的详细地址
            $result[$key]['dog_num'] = $vo['dog_num'];//数量
            $result[$key]['udsc_id_information'] = $vo['udsc_id_information'];//流浪狗特征
            $result[$key]['dog_information'] = $vo['dog_information'];//详细描述
            $result[$key]['user_id'] = $vo['user_id'];//用户ID
            $result[$key]['equipment'] = $vo['equipment'];//设备识别号

            if($vo['user_gender'] == 1){
                $result[$key]['user_sex'] = '男';//狗的主人性别
            }else{
                $result[$key]['user_sex'] = '女';//狗的主人性别
            }
            if($vo['user_attestation'] == 2 || $vo['user_attestation'] == 3){
                $result[$key]['user_attestation'] = '是';//狗的主人认证状态
            }else{
                $result[$key]['user_attestation'] = '否';//狗的主人认证状态
            }

            //主人年龄
            if($vo['user_card'] != ''){
                $result[$key]['user_age'] = $this->getAgeByID($vo['user_card']);
                $result[$key]['address'] = $this->userCard(substr($vo['user_card'],0,2));
            }else{
                $result[$key]['user_age'] = '';
                $result[$key]['address'] = '';
            }
            //设备
            if($vo['equipment']!=''){
                $result[$key]['equipment'] =$vo['equipment'];
            }else{
                $result[$key]['equipment'] ='';
            }
            $result[$key]['total'] = $vo['total'];//留言数量
        }
        $xlsCell  = array(
            array('dog_id','流浪狗的ID'),
            array('dog_status','流浪狗状态'),
            array('dog_time', '发布时间'),
            array('province','省'),
            array('city','市'),
            array('area','区'),
            array('dog_add', '流浪狗被发现的详细地址'),
            array('dog_num', '流浪狗的数量'),
            array('udsc_id_information', '流浪狗特征'),
            array('dog_information', '流浪狗的详细描述'),
            array('user_id', '用户ID'),
            array('equipment', '设备'),
            array('user_sex','主人性别'),
            array('user_attestation','是否认证'),
            array('user_age','主人年龄'),
            array('address','户口所在地'),
            array('equipment','设备'),
            array('total', '留言数量')
        );
        $data = $this->exportExcel($xlsCell,$result);
        return $data;
    }
    /**
     * @return mixed
     * 流浪狗数量柱状图 显示页面
     */
    public function column(){
        $DogModel = new DogModel();
        $AreaModel = new AreaModel();
        $search = input('get.search/a');
        $page = input('get.page');
        $search = $this->search($search, $page);
        $list = $DogModel->strayDogInfo(15,$search);
        $action = '/' . Request::instance()->controller() . '/' . Request::instance()->action();
        $wherePro['level'] = 1;
        if($search[1]!=''){
            $whereCity['pid'] = $search[1];
        }else{
            $whereCity['pid'] = 2;
        }
        if($search[2]!=''){
            $whereDistrict['pid'] = $search[2];
        }else{
            $whereDistrict['pid'] = 52;
        }
        $province =$AreaModel->selectArea($wherePro);
        $city =$AreaModel->selectArea($whereCity);
        $district =$AreaModel->selectArea($whereDistrict);
        $this->assign(
            array(
                'action'=>$action,
                'page'=>$page,
                'search' => $search,
                'province' => $province,
                'city' => $city,
                'district' => $district,
            )
        );
        return $this->fetch();
    }
    /**
     * @return \think\response\Json
     * 流浪狗数量 柱状图
     */
    public function echartsColumn(){
        $search = input('post.search/a');
        if($search[3]!=''&&$search[4]!=''){
            $date_time = $this->prDates($search[3],$search[4],$search[5]);
        }else{
            $date_time = $this->prDates();
        }

        $result = array();
        foreach ($date_time as $key => $vo){
            $result['time'][]=$vo;
            if($search[5]==1){
                $whereHe['u.dog_time'] = array('elt',$vo);
            }else if($search[5]==2){
                $whereHe['u.dog_month'] = array('elt',$vo);
            }else if($search[5]==3){
                $whereHe['u.dog_year'] = array('elt',$vo);
            }else{
                $whereHe['u.dog_time'] = array('elt',$vo);
            }
            if($search[5]==1){
                $whereHe1['u.dog_time'] = array('EQ',$vo);
            }else if($search[5]==2){
                $whereHe1['u.dog_month'] = array('EQ',$vo);
            }else if($search[5]==3){
                $whereHe1['u.dog_year'] = array('EQ',$vo);
            }else{
                $whereHe1['u.dog_time'] = array('EQ',$vo);
            }
            $value  = $this->getArray($search, $whereHe, 1);
            $value1  = $this->getArray($search,$whereHe1, 1);
            $result['value'][]=$value?$value:0;
            $result['value1'][]=$value1?$value1:0;
        }

        $allNum = Db::table('up_dog')->where('dog_type', 1)->count();//获取所有流浪狗记录
        $totalNumS = $this->getNumS($search);//获取所有筛选后同时出现多只流浪狗的记录
        if(!$totalNumS){
            $totalNumS = 0;
        }
        if($allNum != 0){
            $aNumP = number_format($totalNumS/$allNum, 2)*100;//同时出现多只占比
        }else{
            $aNumP = 0;
        }

        $totalNum = $this->getNum($search);//获取所有筛选后流浪狗的记录
        $nNum = $this->getNum($search, 1);//获取待救助流浪狗记录
        if(!$nNum){
            $nNum = 0;
        }
        $yNum = $this->getNum($search, 2);//获取已救助流浪狗记录
        if(!$yNum){
            $yNum = 0;
        }
        $mNum = $this->getNum($search, 3);//获取失踪流浪狗记录
        if(!$mNum){
            $mNum = 0;
        }
        if($totalNum != 0){
            $nNumP = number_format($nNum/$totalNum, 2)*100;//待救助流浪狗占比
            $yNumP = number_format($yNum/$totalNum, 2)*100;//已救助流浪狗占比
            $mNumP = number_format($mNum/$totalNum, 2)*100;//失踪流浪狗占比
        }else{
            $nNumP = 0;
            $yNumP = 0;
            $mNumP = 0;
        }
        $data = array(
            'nNum'      =>   $nNum,
            'nNumP'     =>   $nNumP,
            'yNum'      =>   $yNum,
            'yNumP'     =>   $yNumP,
            'mNum'      =>   $mNum,
            'mNumP'     =>   $mNumP,
            'aNumP'     =>   $aNumP,
            'result'    =>   $result
        );
        return json($data);
    }
    /**
     * @param $search    查询条件
     * @param $status   救助状态
     * @return $num     统计记录数量
     */
    public function getNum($search, $status=''){
        $where = array();
        //地区查询
        if($search[0]!=''){
            $where['u.area_sheng'] = array('=',$search[0]);
        }
        if($search[1]!=''){
            $where['u.area_shi'] = array('=',$search[1]);
        }
        if($search[2]!=''){
            $where['u.area_qu'] = array('=',$search[2]);
        }
        //流浪狗
        $where['u.dog_type'] = 1;
        //流浪狗状态
        if($status != ''){
            $where['u.dog_status'] = $status;
        }
        //时间条件
        if($search[3] != '' && $search[4] != ''){
            $date_time = $this->prDates($search[3], $search[4], $search[5]);
        }else{
            $date_time = $this->prDates();
        }
        $count = count($date_time);
        if($search[5] == ''){//默认年月日
            $start = $date_time[0];
            $end = $date_time[$count-1];
            $whereMap['u.dog_time'] = array('between',array($start,$end));
        }else{//证明按了点击按钮
            $whereMap = $this->dateArray($search,$count,$date_time);
        }
        //记录数
//        $num = Db::table('up_dog')->alias('u')->where($where)->where($whereMap)->count();
        $num = Db::table('up_dog')->alias('u')->where($where)->where($whereMap)->sum('dog_num');
        return $num;
    }
    /**
     * @param $search    查询条件
     * @param $status   救助状态
     * @return $num     统计同时多只出现记录数量
     */
    public function getNumS($search){
        $where = array();
        //地区查询
        if($search[0]!=''){
            $where['u.area_sheng'] = array('=',$search[0]);
        }
        if($search[1]!=''){
            $where['u.area_shi'] = array('=',$search[1]);
        }
        if($search[2]!=''){
            $where['u.area_qu'] = array('=',$search[2]);
        }
        //流浪狗
        $where['u.dog_type'] = 1;
        //同时出现多只
        $where['u.dog_num'] = array('>', 1);
        //时间条件
        if($search[3] != '' && $search[4] != ''){
            $date_time = $this->prDates($search[3], $search[4], $search[5]);
        }else{
            $date_time = $this->prDates();
        }
        $count = count($date_time);
        if($search[5] == ''){//默认年月日
            $start = $date_time[0];
            $end = $date_time[$count-1];
            $whereMap['u.dog_time'] = array('between',array($start,$end));
        }else{//证明按了点击按钮
            $whereMap = $this->dateArray($search,$count,$date_time);
        }
        //记录数
        $num = Db::table('up_dog')->alias('u')->where($where)->where($whereMap)->count();
        return $num;
    }
    /**
     * @param $search
     * @param $whereS
     * @param $type
     * @return int|string
     * 查询柱状图和折线图需要的数据
     */
    public function getArray($search, $whereMap, $type){
        $where = '';
        if($search[0]!=''){
            $where['u.area_sheng'] = array('=',$search[0]);
        }
        if($search[1]!=''){
            $where['u.area_shi'] = array('=',$search[1]);
        }
        if($search[2]!=''){
            $where['u.area_qu'] = array('=',$search[2]);
        }
        $where['u.dog_type'] = $type;
        $branch = Db::table('up_dog')->alias('u')
            ->where($where)
            ->where($whereMap)
            ->count();
        //总的数据
        return $branch;
    }

    /***
     * @return \think\response\Json
     * 删除
     */
    public function delDog(){
        $ids = strtoarray(input('post.ids'));
        $DogFamilyModel = new DogModel();
        $where['dog_id'] = array('In', $ids);
        $result = $DogFamilyModel->where($where)->delete();
        if ($result) {
            return $this->api_success('操作成功');
        } else {
            return $this->api_dbError();
        }
    }
    public function details(){
        $DogModel = new DogModel();
        $dog_id = input('dog_id');
        $data = Db::name('dog')
            ->alias('a')
            ->join('up_u_user uuu', 'uuu.user_id = a.user_id', 'left')
            ->join('up_area ua1', 'ua1.district_id = a.area_sheng', 'left')
            ->join('up_area ua2', 'ua2.district_id = a.area_shi', 'left')
            ->join('up_area ua3', 'ua3.district_id = a.area_qu', 'left')
            ->where('dog_id', $dog_id)
            ->field('a.dog_click_num,a.dog_id, a.dog_release_time, a.dog_status, ua1.district as province, ua2.district as city, 
            ua3.district as district, a.dog_num, a.udsc_id, a.udsc_id_information, 
            uuu.user_username, uuu.user_phone, uuu.user_attestation, uuu.user_gender, uuu.user_card')
            ->find();
        if(!$data){
            return $this->api_dbError();
        }
        $udsc_id['udsc_id'] =array('IN', trim($data['udsc_id'], ','));
        $udsc_name = Db::name('dog_strat_characteristic')->where($udsc_id)->column('udsc_name');//获取狗的特征
        if($udsc_name){
            if($data['udsc_id_information'] != ''){
                $data['udsc_id_information'] = implode(',', $udsc_name).','.$data['udsc_id_information'];
            }else{
                $data['udsc_id_information'] = rtrim(implode(',', $udsc_name), ',');
            }
        }
        //留言数量
        $whereMap['m_dog_id'] = $data['dog_id'];
        $count = Db::name('message')->where($whereMap)->count();
        $data['total'] = $count;
        //主人年龄
        if($data['user_card'] != ''){
            $data['user_card'] = $this->getAgeByID($data['user_card']);
        }else{
            $data['user_card'] = '';
        }
        $this->assign(
            array(
                'data' => $data,
                'user_gender'=>$DogModel::$user_gender,
                'dog_status'=>$DogModel::$dog_status,
            )
        );
        return $this->fetch();
    }
}